#!/usr/bin/env python
# -*- coding: utf-8 -*-

'''
cron作业handle模块
'''

from lib.myweb import WebApplication

from common.myconfig import CONF
from common.mydata import ModelCharge

from handle.charge import FilterCharge
from handle.charge import ValidatorCharge


class HandleCron(WebApplication):
    'cron作业handle'
    _HANDLE_NAME = 'cron'  # handle名称，用于模板前缀
    _PATH_PREFIX = '/_in'  # 一级路径名称，用于解析path

    def action_confirm(self):
        '定期向支付平台询问以更新订单状态'
        import urllib
        import cgi
        from igor import urlfetch
        from igor import logging

        self._render.mode = 'plain'

        pay_check_url = CONF['pay_check_url']
        mod_chg = ModelCharge()

        # 检查充值订单信息
        charge_infos = mod_chg.select_by_unpaid()
        if not charge_infos:
            logging.log('No unpaid charge order.')
            self._render.view = 'No unpaid charge order.'
            return

        # 请求支付接口检查支付订单号支付状态
        pay_dict = [('pay_sn', info['pay_sn']) for info in charge_infos]
        pay_dict.append(('service_sn', CONF['service_sn']))
        # 根据上面的内容生成签名
        sign = FilterCharge.get_signature(pay_dict, CONF['service_key'])
        pay_dict.append(('sign', sign))

        pay_data = urllib.urlencode(pay_dict)
        pay_header = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = urlfetch.fetch(
                url=pay_check_url,
                payload=pay_data,
                method='POST',
                headers=pay_header)

        # 检查响应内容
        res_content = response.content
        res_forms = cgi.parse_qs(res_content)
        form_checked = {}
        for pay_status in ModelCharge.PAY_STATUS:
            form_checked[pay_status] = []
            pay_sn_list = res_forms.get(pay_status, [])
            for pay_sn in pay_sn_list:
                if ValidatorCharge.check(pay_sn, 'pay_sn'):
                    form_checked[pay_status].append(pay_sn)

        # 检查签名
        res_form = {'sign': res_forms.get('sign', [''])[0]}
        sign_info, error_type = ValidatorCharge.check_from_dict(
                res_form, ['sign', ])
        if error_type:
            self._render.view = error_type
            return

        content = []
        for pay_status in ModelCharge.PAY_STATUS:
            for pay_sn in form_checked[pay_status]:
                content.append((pay_status, pay_sn))
        sign = FilterCharge.get_signature(content, CONF['service_key'])
        if sign != sign_info['sign']:
            self._render.view = 'sign_error'
            return

        # 取消充值订单
        pay_sn_list = form_checked['canceled']
        for pay_sn in pay_sn_list:
            mod_chg.update_canceled(pay_sn)

        logging.log('%s order canceled.' % len(pay_sn_list))
        self._render.view = '%s order canceled.\n' % len(pay_sn_list)

        # 修改充值订单为已付款
        pay_sn_list = form_checked['paid']
        for pay_sn in pay_sn_list:
            mod_chg.update_paid(pay_sn)

        logging.log('%s order paid.' % len(pay_sn_list))
        self._render.view += '%s order paid.' % len(pay_sn_list)


application = HandleCron()
